package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/user")
public class UserServlet extends HttpServlet {

    //1. 根据请求参数调用不同的方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 得到请求参数
        String cmd = req.getParameter("cmd");
        //1.2 根据请求参数调用方法
        if (StringUtils.isNotBlank(cmd)){
            if ("login".equals(cmd)){
                login(req,resp);
            }
            if ("info".equals(cmd)){
                info(req,resp);
            }
        }
    }

    //2. 用户登录
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //2.1 定义r对象
        R r = R.ok().data("token", 1);
        //2.2 转换成json串
        resp.getWriter().println(JSON.toJSONString(r));
        //2.3 刷新页面
        resp.getWriter().flush();
    }

    //3. 用户信息
    private void info(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //3.1 定义r对象
        R r = R.ok().data("name", "admin")
                    .data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        //3.2 输出到前端页面
        resp.getWriter().println(JSON.toJSONString(r));
        //3.3 刷新页面
        resp.getWriter().flush();

    }

}
